package controle;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

import javax.swing.JOptionPane;

import presentation.ModuleDialog;

import abstraction.Cours;
import abstraction.Module;

/** controleur qui ajoute un module
 * 
 * @author PICOSSON
 *
 */
public class ControlJButtonSaveModule implements ActionListener {

	private Cours modele;
	private boolean creation;
	private ModuleDialog parent;

	public ControlJButtonSaveModule(ModuleDialog parent, Cours modele,
			boolean creation) {
		this.modele = modele;
		this.creation = creation;
		this.parent = parent;
	}

	public void actionPerformed(ActionEvent e) {
		Module m;
		if(creation){
			m = new Module(parent.getNom(), parent.getResponsable());
		}
		else
			m = new Module(parent.getId_module(),parent.getNom(), parent.getResponsable());

		try {
			if(m.getNom().length() < 1)
				throw new Exception("Il n'y a pas de nom de module.");
			
			if(m.getResponsable().length() < 1)
				throw new Exception("Il n'y a pas de responsable.");
			
			if(creation && this.modele.findModule(m.getNom()) != null)
				throw new Exception("Le module existe déjà");
			
			System.out.println("/"+m.getNom() + "/" + m.getResponsable()+"/");
			modele.saveModule(m, creation);
			parent.setVisible(false);
		} catch (Exception e1) {
			JOptionPane.showMessageDialog(parent, "On ne peut pas! "+ e1.getMessage(), "Erreur!",
					JOptionPane.ERROR_MESSAGE);
		}
	}

}
